package com.cyf;

import com.cyf.util.BasicProperties;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.servlet.MultipartConfigElement;
import java.io.File;

/**
 * @author cage
 */
@SpringBootApplication //等同于 @Configuration @EnableAutoConfiguration @ComponentScan
@EnableScheduling
@EnableTransactionManagement // 启注解事务管理，等同于xml配置方式的 <tx:annotation-driven />
@MapperScan("com.cyf.db.mapper")
public class PmCloudCSvrApp {

    private static final Logger logger = LoggerFactory.getLogger(PmCloudCSvrApp.class);

    @Autowired
    private BasicProperties basicProperties;

    public static void main(String[] args) {
        SpringApplication.run(PmCloudCSvrApp.class, args);
    }

    @Bean
    public EmbeddedServletContainerFactory servletContainerFactory() {
        TomcatEmbeddedServletContainerFactory factory =
                new TomcatEmbeddedServletContainerFactory() {
                    @Override
                    protected void postProcessContext(Context context) {
                        //SecurityConstraint必须存在，可以通过其为不同的URL设置不同的重定向策略。
                        // https的请求
                        SecurityConstraint securityConstraint = new SecurityConstraint();
                        securityConstraint.setUserConstraint("CONFIDENTIAL");
                        SecurityCollection collection = new SecurityCollection();
                        //	collection.addPattern("/*");
                        for (String pattern : basicProperties.getHttpsUrlPatterns()) {
                            collection.addPattern(pattern);
                        }
                        securityConstraint.addCollection(collection);
                        context.addConstraint(securityConstraint);

                        // http的请求
                        SecurityConstraint securityConstraintHttp = new SecurityConstraint();
                        securityConstraintHttp.setUserConstraint("NONE");
                        SecurityCollection collectionHttp = new SecurityCollection();
                        for (String pattern : basicProperties.getHttpUrlPatterns()) {
                            collectionHttp.addPattern(pattern);
                        }
                        securityConstraintHttp.addCollection(collectionHttp);
                        context.addConstraint(securityConstraintHttp);
                    }
                };
        factory.addAdditionalTomcatConnectors(createHttpConnector());
        return factory;
    }

    private Connector createHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setSecure(false);
        connector.setPort(basicProperties.getHttpPort());
        connector.setRedirectPort(basicProperties.getServerPort());
        return connector;
    }

    /**
     * 解决异常：The temporary upload location is not valid
     * http://wuzhaoyang.me/2017/06/07/spring-multipartexception-location-not-valid.html
     * 前端Ajax上传一张图片，服务端将文件流临时保存在文件夹里(这个文件夹由spring boot在启动的时候新建)。
     * /tmp文件夹的有自动cleanup机制，/tmp文件夹的文件10天未更新会被移除，/var/tmp文件夹的文件是30天。
     * 思路：指定目录，将防止文件夹被自动删除。
     * @return
     */
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        String absolutePath = new File("").getAbsolutePath();
        logger.info("absolutePath ===== {}", absolutePath);
        String location = absolutePath + "/data/tmp";
        File file = new File(location);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            logger.info("创建文件夹({})：{}", location, mkdirs);
        } else {
            logger.info("SpringBoot内置Tomcat缓存文件目录：{}", location);
        }
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }
}
